<template>
<div class="graph-panel">
  <div class="graph-switch" v-if="(graphTypeName !== '卡片') && graphSwitch">
    <Dropdown placement="bottom-end" @on-click="switchGraphType">
      <a>
        {{graphTypeName}}
        <Icon type="ios-arrow-down"></Icon>
      </a>
      <DropdownMenu slot="list" v-if="graphChartList.length > 0">
        <DropdownItem v-for="graphChart in graphChartList" :name="graphChart" :key="graphChart">{{graphChart}}</DropdownItem>
      </DropdownMenu>
    </Dropdown>
  </div>
    <chart-table ref="panel" v-if="graphTypePanel=='table'"  :graph-options="graphOptions" :tablist="tablist" :table-column='tableColumn'></chart-table>
    <video loop autoplay :src="videoSrc" v-else-if="graphTypePanel=='video'"></video>
    <echart-card ref="panel" v-else-if="graphTypePanel === 'card'" :graph-options="graphOptions" :config="config"></echart-card>
    <echart-text ref="panel" v-else-if="graphTypePanel === 'text'" :graph-options="graphOptions" :config="config"></echart-text>
    <echart-img ref="panel" v-else-if="graphTypePanel === 'img'" :graph-options="graphOptions" :config="config"></echart-img>
    <echart-panel ref="panel"  v-else :graph-options="graphOptions"   :table-column='tableColumn'></echart-panel>
    <!-- <component ref="panel" :is="comptName" :graph-options="graphOptions" :tablist="tablist" :table-column='tableColumn'></component> -->
</div>
</template>

<script>
import getData          from 'getData'
import EchartPanel      from './echarts-panel'
import chartTable       from  './chart-table'
import EchartCard       from  './echart-card'
import EchartText       from  './echart-text'
import EchartImg       from  './echart-img'
import {chartUtil,chartOptions} from '@/assets/js/graph-chart'
import util from 'util'
const GRAPH_TYPE = {
  '表格': 'table',
  '柱状图': 'bar',
  '条形图': 'bar_type',
  '折线图': 'line',
  '计量图': 'gauge',
  '折线面积图': 'line_area',
  '柱状堆叠图': 'bar_pile',
  '条形堆叠图': 'bar_type_pile',
  '散点图': 'scatter',
  '饼图': 'pie',
  '环形图': 'pie_more',
  '树图': 'tree',
  '地图': 'map',
  '卡片': 'card',
  '文本': 'text',
  '图片': 'img',
  '漏斗图': 'funnel'
}
export default {
    components: {
        EchartPanel,chartTable, EchartCard, EchartText, EchartImg
    },
    props: {
        datasource: {
            type: Object
        },
        graphType: {
            type: String
        },
        graphOptions: {
            type: Object
        },
        paneltype:{
            type: String,
            default:'show'
        },
        videoSrc: {
          type: String,
          default: ''
        },
        config: {
          type:Object,
          default:function () {
              return {}
          }
        },
        graphSwitch: {
          type: Boolean,
          default: false
        }
    },
    watch: {
        datasource: {
            deep: true,
            handler (val,old) {
              console.log('changeDatasource')
                if (!val.isNumberChange) {
                  if(val.groups.length === old.groups.length  && val.numbers.length === old.numbers.length){
                      this.queryData(false);
                  }else{
                      this.queryData(true);
                  }
                }
            }
        },
        // graphType(val) {
        //     this.setGraphType(val);
        // }
    },
    computed: {
        comptName() {
            switch(this.graphType) {
                case 'table' :
                    return 'chartTable'
                default:
                    return 'EchartPanel';
            }
        },
        graphTypePanel () {
          if (this.graphTypeSwitch) {
            return this.graphTypeSwitch
          }	else {
            return this.graphType || ''
          }
        }
    },
    data () {
        return {
            tablist:[],
            tableColumn:'',
            graphChartList: [],
            graphTypeName: '',
            graphTypeSwitch: ''
        }
    },
    methods: {
        init() {
          this.queryData();
            // if(this.graphType){
            //     this.queryData();
            // }
        },
        resizeChart() {
          let noResizeType = ['talbe', 'card', 'text', 'img']
          if (noResizeType.indexOf(this.graphType) === -1) {
            this.$refs.panel.resize();
          }
        },
        refresh() {
            this.$refs.panel.refresh();
        },
        getDataURL(){
            return  this.$refs.panel.getDataURL();
        },
        judgeGraphType(){
          for (const key in GRAPH_TYPE) {
            if (GRAPH_TYPE.hasOwnProperty(key)) {
              const type = GRAPH_TYPE[key];
              if (type === this.graphType) {
                this.graphTypeName = key
              }
            }
          }
          let groupLength = this.datasource.groups.length
          let numberLength = this.datasource.numbers.length
            //只有一个维度
            var types =[];
            //table  表格展示
            //tree
            if(groupLength>0|| numberLength>0){
                types.push('表格');
                types.push('文本');
                types.push('图片');
            }
            if(groupLength==2 && numberLength==0){
                types.push('柱状图');
                types.push('条形图');
                types.push('折线图');
            }
            if(groupLength==0 && numberLength==1){
                types.push('计量图');
            }
            if(groupLength<=2 && numberLength>=1){
                types.push('柱状图');
                types.push('条形图');
            }
            if(groupLength>0 &&groupLength<=2 && numberLength>=1){
                types.push('折线图');
                types.push('折线面积图');
            }
            if(0<groupLength&& groupLength<=2 && numberLength>=2){
                types.push('柱状堆叠图');
                types.push('条形堆叠图');
            }
            if(groupLength==1 && numberLength==2){
                types.push('散点');
            }
            if(groupLength==1 && numberLength==0){
                types.push('饼图');
            }
            if((groupLength==1 && numberLength==1)||(groupLength==0&& numberLength>=1)){
                types.push('饼图');
                types.push('环形图');
                types.push('漏斗图');
            }
            // if(groupLength>=2 && numberLength==1){
            //     types.push('嵌套环形饼图');
            // }
            // if(groupLength>=1 && numberLength<=1){
            //     types.push('树图');
            // }
            // if(groupLength==1 && numberLength>=1){
            //     types.push('地图');
            // }
            // if (groupLength >= 0 && numberLength === 1) {
            //   types.push('卡片');
            // }
            // 当前维度  支持可以选择的图表类型集合
            this.graphChartList =types;
        },
        queryData(change) {
            // if(!this.graphType){
            //     return ;
            // }
            // console.log('数据源改变 重新查询数据 |','是否改变数值维度：'+change  ,this.graphType)
            console.log('datasource: ')
            console.log(JSON.stringify(this.datasource))
            // if(this.datasource.datasourceId!=null  && this.datasource.datasourceType !=null){
                // getData.post('queryViewData', this.datasource).then((res) => {
                let kpiCode = ''
                if (this.datasource && this.datasource.numbers) {
                  for (let i = 0; i < this.datasource.numbers.length; i++) {
                    const num = this.datasource.numbers[i];
                    if (i === 0) {
                      kpiCode += num.kpiCode
                    } else {
                      kpiCode += ',' + num.kpiCode
                    }
                  }
                }

                getData.get('getKpiValuesByDimeAndKpiCode', {params: {kpiCode}}).then((res) => {
                    if (res.status == 200 && res.data.resultCode == 0) {
                      if (res.data.data.length === 1) {
                        return
                      }
                        this.tablist =util.util.cloneObj(res.data.data);
                        this.tableColumn =this.datasource.groups.length;
                        if(this.datasource.groups.length>0){
                            if (this.datasource.groups.length==1) {
                                //单维度
                                var list =res.data.data;
                                var sets =[];
                                var item ;
                                for(var i  =1;i<list[0].length;i++){
                                    item ={
                                        dimensions:[],
                                        source:[]
                                    };
                                    item.dimensions.push(list[0][0]);
                                    item.dimensions.push(list[0][i]);
                                    for(var j =1;j<list.length;j++){
                                        item.source.push([list[j][0],list[j][i]]);
                                    }
                                    sets.push(item);
                                }
                                this.$set(this.graphOptions,'dataset',sets)
                            }else if(this.datasource.groups.length==2){
                                //双维度
                                //第一列 为二维度
                                //第二列 为一维度
                                var list =res.data.data;
                                var sets ={
                                    dimensions:list[0]
                                }
                                sets.dimensions.splice(0,1)
                                list.splice(0,1);
                                var xtwo =[];

                                for(var i  in list ){
                                    xtwo.push(list[i][0]);
                                }
                                for(var i  in list ){
                                    list[i].splice(0,1);
                                }
                                for(var i =0;i<list.length;i++){
                                    list[i][0]+='_'+i;
                                }
                                sets.source =list;
                                sets.xdata =xtwo;
                                this.$set(this.graphOptions,'dataset',sets) ;
                            }
                            // 计算支持推行类型
                            this.judgeGraphType()
                            /*
                            1. change 编辑的时候，切换数值和维度，才初始化图表参数，全部重新渲染
                            2. 其他情况  继承渲染，例如初始化函数无法保存，需要重新生成，多维度需要重新生成部分参数*/
                            console.log('before((((((')
                            console.log(JSON.stringify(this.graphOptions))
                                new chartOptions(this,{
                                    type:this.graphType,
                                    groupnum:this.datasource.groups.length ,
                                    clomnnum:this.datasource.numbers.length,
                                    groups: this.datasource.groups,
                                    numbers: this.datasource.numbers,
                                    extendState:!change
                                }).initChartOptions();
                                // console.log('after))))))))')
                            // console.log(JSON.stringify(this.graphOptions))
                        }

                    } else {
                      // this.$Message.error({
                      //   content: res.data.errorInfo.errorMsg || '系统错误',
                      //   duration: 1.5
                      // })
                        console.error(res);
                    }
                });
            // }else{
            //     console.error('数据源数据存在为空');
            // }

        },
        switchGraphType(typeName) {
          let vm = this
          let type = GRAPH_TYPE[typeName]
          vm.graphTypeSwitch = type
          vm.graphTypeName = typeName
          vm.$nextTick(function () {
            if (type) {
                new chartOptions(vm,{
                    type: type,
                    groupnum:vm.datasource.groups.length ,
                    clomnnum:vm.datasource.numbers.length,
                    groups: vm.datasource.groups,
                    numbers: vm.datasource.numbers,
                    extendState: true
                }).initChartOptions();
            }
          })
        },
        // setGraphType(val) {
        //     if (val) {
        //         for (var index in this.options.series) {
        //             this.options.series[index].type = val;
        //         }
        //         if(this.options.series.length<this.options.dataset.source[0].length-1 && this.options.dataset.source!=null){
        //             for (var i=this.options.series.length;i<this.options.dataset.source[0].length-1;i++) {
        //                 this.options.series.push( {type: val});
        //             }
        //         }
        //     }
        // }
    },
    mounted() {
        // this.setGraphType(this.graphType);
        this.init();
    }

}
</script>

<style>
.graph-panel{
  position: relative;
  width: 100%;
  height: 100%;
}
.graph-switch {
  position: absolute;
  right: 10px;
  top: 6px;
  z-index: 9999;
}
.graph-switch {
  display: none;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 2px 8px;
}
.graph-panel:hover .graph-switch {
  display: block;
}
.graph-switch a {
  color: #fff;
  font-size: 12px;
}
.graph-switch /deep/ .ivu-dropdown-menu {
  min-width: 70px;
}
.graph-switch /deep/ .ivu-dropdown .ivu-select-dropdown {
  background-color: rgba(0, 0, 0, 0.6);
}
.graph-switch /deep/ .ivu-dropdown-item {
    padding: 3px 8px;
    color: #fff;
    font-size: 12px !important;
}
.graph-switch /deep/ .ivu-dropdown-item:hover {
  background-color: rgba(0, 0, 0, 0.7);
}
</style>
